// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 5;
// 预测结果
const predictResults = [];

/**
 * ✨ 基于最近连续号趋势策略
 * - 如果近几期中连续号码频繁出现，则选新一组连续号。
 */
function select32ByRecentConsecutive(temp) {
  const consecutivePairs = [];

  // 找到最近的连续号码对
  for (let i = 1; i < temp.length; i++) {
    const currentNum = parseInt(temp[i].number, 10);
    const prevNum = parseInt(temp[i - 1].number, 10);
    
    // 判断是否为连续号码
    if (currentNum === prevNum + 1) {
      consecutivePairs.push([prevNum, currentNum]);
    }
  }

  // 如果有连续号对，选择新的连续号
  const selected = [];
  if (consecutivePairs.length > 0) {
    // 获取当前的连续对
    consecutivePairs.forEach(pair => {
      const start = pair[1];  // 当前连续号的最大值
      const nextConsecutivePair = [start + 1, start + 2]; // 下一组连续号
      selected.push(nextConsecutivePair[0], nextConsecutivePair[1]);
    });
  }

  // 如果选出的号码不足32个，则从所有号码中按顺序补充
  if (selected.length < 32) {
    const remain = allNumbers.filter((n) => !selected.includes(n));
    const needed = 32 - selected.length;
    selected.push(...remain.slice(0, needed));  // 从未选中的号码中按顺序补充
  }

  return selected;
}

// ✅ 主循环
let correct = 0;
let maxWrongStreak = 0;
let currentWrongStreak = 0;

allValues.forEach((item, index) => { 
  const temp = useWindow ? allValues.slice(index - windowSize, index) : allValues.slice(0, index);

  if (temp.length === 0) return;

  const selectedNumbers = select32ByRecentConsecutive(temp);

  if (selectedNumbers.length !== 32) {
    throw new Error("选出的32个号码数量不正确");
  }

  try {
    const isHit = checkAccuracy(selectedNumbers, item.number);
    if (isHit) {
      correct += 1;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak += 1;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }
  } catch (err) {
    console.error(`❌ checkAccuracy error at index ${index}: ${err.message}`);
  }
});

// ✅ 输出统计结果
const total = allValues.length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);
